# from channels.generic.websocket import WebsocketConsumer
# from channels.exceptions import StopConsumer
#
#
# import json
# from channels.layers import get_channel_layer
# from asgiref.sync import async_to_sync
# import random
# from utils.myredis import myredis
# from ollama import Client
#
# userlist = []
#
#
# def process_string(input_string, userstr):
#     index = input_string.find(userstr)
#     if index != -1:
#         return input_string[index + len(userstr):]
#     else:
#         return None
#
#
# def sendmes(ask):
#     client = Client(
#         host='http://localhost:11434'  # 大模型所在服务器的地址
#     )
#     response = client.chat(model='nezahatkorkmaz/deepseek-v3', messages=[
#         {
#             'role': 'system',
#             'content': '你是一个乐于助人的助手'
#         },
#         {
#             'role': 'user',
#             'content': ask,
#         },
#     ])
#     print("@@@@")
#     print(response['message']['content'])
#     return response['message']['content']
#
#
# # 初始化三个客服
# kelist = [1001, 1002, 1003]
#
#
# class ChatConsumer(WebsocketConsumer):  # 继承WebsocketConsumer
#     #    room_name = 'chat_all_data'
#     def websocket_connect(self, message):
#         print("有人进行连接了。。。。")
#         self.group_name = self.scope['url_route']['kwargs']['group']
#
#         # 判断是用户还是客服  user1
#         # 如果是用户，分配客服，加入房间号，并且推荐消息到客服房间号
#         if self.group_name.find('user') >= 0:
#             arr = self.group_name.split("user")
#             number = hash(arr[1]) % len(kelist)
#             kefuid = kelist[number]
#             # user11001
#             room = str(self.group_name) + str(kefuid)
#             async_to_sync(self.channel_layer.group_add)(room, self.channel_name)
#             channel_layer = get_channel_layer()
#             kroom = 'kefu' + str(kefuid)
#             async_to_sync(channel_layer.group_send)(
#                 str(kroom),  # 房间组名
#                 {
#                     'type': 'send_to_chrome',  # 消费者中处理的函数
#                     'data': {"id": arr[1], "name": str(arr[1]) + '号用户'}
#                 }
#             )
#         else:
#             async_to_sync(self.channel_layer.group_add)(self.group_name, self.channel_name)
#         # 如果是客服加入客服房间号
#
#         # aicode = '1001'
#         # cls = ChatConsumer
#         # self.room_group_name = cls.room_name
#         # print(self.scope['url_route']['kwargs'])
#         # self.group_name = self.scope['url_route']['kwargs']['group']
#         # user1
#         # if self.group_name.find('user')>=0:
#         #     #用户 user11001
#         #     room = self.group_name + aicode
#         #     async_to_sync(self.channel_layer.group_add)('user11001', self.channel_name)
#         #     #当前的用户信息发送给客服{"userid":1,'name':'zs'}
#
#         #     userid = process_string(self.group_name,'user')
#
#         #     name ='zs'+str(userid)
#         #     if name not in userlist:
#         #         print("*****"+name)
#         #         channel_layer = get_channel_layer()
#         #         async_to_sync(channel_layer.group_send)(
#         #             str(aicode),#房间组名
#         #             {
#         #                 'type':'send_to_chrome', #消费者中处理的函数
#         #                 'data':{"id":userid,"name":name}
#         #             }
#         #         )
#         #         userlist.append(name)
#
#         # 用户链接，给用户发历史消息
#         # message =r.get_str(room)
#         # if message:
#         #     message=json.loads(message)
#         #     for i in message:
#         #         channel_layer = get_channel_layer()
#         #         async_to_sync(channel_layer.group_send)(
#         #             room,#房间组名
#         #             {
#         #                 'type':'send_to_chrome', #消费者中处理的函数
#         #                 'data':i
#         #             }
#         #         )
#
#         # 将用户加入用户列表
#         # user ={"id":userid,"name":name}
#         # ulist =r.get_str('userlist')
#         # flag = True
#         # if ulist:
#         #     ulist = json.loads(ulist)
#         #     for i in ulist:
#         #         if userid == i['id']:
#         #             flag = False
#         # else:
#         #     ulist=[]
#         # if flag:
#         #     ulist.append(user)
#         #     r.set_str('userlist',json.dumps(ulist))
#
#         # else:
#         # 客服
#         # async_to_sync(self.channel_layer.group_add)(str("1"), self.channel_name)
#         # self.group_name = "2"
#         # async_to_sync(self.channel_layer.group_add)(str(self.group_name), self.channel_name)
#         # channel_layer = get_channel_layer()
#         # ulist =r.get_str('userlist')
#         # if ulist:
#         #     ulist =json.loads(ulist)
#         #     for i in ulist:
#         #         async_to_sync(channel_layer.group_send)(
#         #             str(aicode),#房间组名
#         #             {
#         #                 'type':'send_to_chrome', #消费者中处理的函数
#         #                 'data':{"id":i.id,"name":i.name}
#         #             }
#         #         )
#
#         # 有客户端向后端发送 WebSocket 连接的请求时，自动触发(握手)
#         self.accept()
#
#     def websocket_receive(self, message):
#         # 浏览器基于 WebSocket 向后端发送数据，自动触发接收消息
#         # 消息持久化 mysql  redis
#         # ---ai start
#         mes = message['text']
#         # print(mes)
#         answer = sendmes(mes)
#         channel_layer = get_channel_layer()
#
#         async_to_sync(channel_layer.group_send)(
#             'user11001',  # 房间组名
#             {
#                 'type': 'send_to_chrome',  # 消费者中处理的函数
#                 'data': {"message": answer, 'from': 'user11001'}
#             }
#         )
#     # ---ai end
#     #     print(message['text'])
#     #     data = json.loads(message['text'])
#     #     message = data['mes']
#     #     room = str(data['room'])+'1001'
#
#     #     userid = process_string(str(data['room']),'user')
#     # # #    self.send(message)
#     #     channel_layer = get_channel_layer()
#
#     #     async_to_sync(channel_layer.group_send)(
#     #         room,#房间组名
#     #         {
#     #             'type':'send_to_chrome', #消费者中处理的函数
#     #             'data':{"message":message,'from':str(userid)}
#     #         }
#     #     )
#
#     # redis字符串，key:房间号，value:消息列表
#     # 客服或者用户调用send的时候
#
#     # 获取历史消息
#     # messvalue = r.str_get(room)
#     # if messvalue:
#     #     mess =json.loads(messvalue)
#     # else:
#     #     mess=[]
#     # mess.append({"message":message,'from':str(userid)})
#     # r.str_set(room,json.dumps(mess))
#     def websocket_disconnect(self, message):
#         # 客户端向服务端断开连接时，自动触发
#         print("连接断开！！")
#         self.group_name = self.scope['url_route']['kwargs']['group']
#
#         async_to_sync(self.channel_layer.group_discard)(
#             self.group_name,
#             self.channel_name
#         )
#         raise StopConsumer()
#
#     # 自定义的处理房间组内的数据
#     def send_to_chrome(self, event):
#         try:
#             data = event.get('data')
#             # 接收房间组广播数据，将数据发送给websocket
#             self.send(json.dumps(data, ensure_ascii=False))
#         except Exception as e:
#             pass
#
#
#

from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer

from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer

import json
from ollama import Client


def process_string(input_string, userstr):
    index = input_string.find(userstr)
    if index != -1:
        return input_string[index + len(userstr):]
    else:
        return None


list = []


def sendmes(ask):
    client = Client(
        host='http://localhost:11434'  # 大模型所在服务器的地址
    )

    response = client.chat(model='nezahatkorkmaz/deepseek-v3', messages=[
        {
            'role': 'system',
            'content': '你是一个乐于助人的助手'
        },
        {
            'role': 'user',
            'content': ask,
        },
    ])
    print("@@@@")
    print(response['message']['content'])
    return response['message']['content']


class ChatConsumer(WebsocketConsumer):  # 继承WebsocketConsumer
    #    room_name = 'chat_all_data'{"1":"242345345"}
    def websocket_connect(self, message):
        print("有人进行连接了。。。。")
        # kefulist = [1001,1002,1003,1004]
        # userid=1  #user10
        # number = hash(userid)%len(kefulist)
        # kefuid = kefulist[number]
        kefuid = 1001
        # 获取参数
        self.group_name = self.scope['url_route']['kwargs']['group']
        print(self.group_name, "==============================================")
        # 判断用户还是客服
        if self.group_name.find("user") >= 0:

            room = self.group_name + str(kefuid)
            print(room, "+++++++++++++++++++++++++++++++++++++++++++++++++")
            # 如果是用户 用userid+kefuid建立房号，并且把当前用户发送到客服的房间号
            async_to_sync(self.channel_layer.group_add)(room, self.channel_name)
            channel_layer = get_channel_layer()
            async_to_sync(channel_layer.group_send)(
                str(kefuid),  # 房间组名
                {
                    'type': 'send_to_chrome',  # 消费者中处理的函数
                    'data': {"id": self.group_name, "name": "用户" + str(self.group_name)}
                }
            )
        else:
            # 如果是客服，用kefuid建立房间号
            async_to_sync(self.channel_layer.group_add)(str(kefuid), self.channel_name)

        # 有客户端向后端发送 WebSocket 连接的请求时，自动触发(握手)
        self.accept()

    def websocket_receive(self, message):
        # {"mes":mes.value,"to":puser.value}
        kefuid = 1001
        mess = json.loads(message['text'])
        type = mess['type']
        print(mess, "mess《|||||||||||||||||||||||||||||||||||||||")
        userid = mess['to']
        room = userid + str(kefuid)
        channel_layer = get_channel_layer()
        async_to_sync(channel_layer.group_send)(
            room,  # 房间组名
            {
                'type': 'send_to_chrome',  # 消费者中处理的函数
                'data': {"mes": mess['mes'], "type": type}
            }
        )
        # 这是开始ai的数据
        # ---ai start
        message = message['text']
        print(message)
        answer = sendmes(message)
        channel_layer = get_channel_layer()

        async_to_sync(channel_layer.group_send)(
            'user11001',  # 房间组名
            {
                'type': 'send_to_chrome',  # 消费者中处理的函数
                'data': {"mes": answer, 'from': 'user11001'}
            }
        )

        # ---ai end

        data = json.loads(message['text'])
        message = data['message']
        room = str(data['from'])
        #    self.send(message)
        channel_layer = get_channel_layer()

        async_to_sync(channel_layer.group_send)(
            room,  # 房间组名
            {
                'type': 'send_to_chrome',  # 消费者中处理的函数
                'data': message
            }
        )

    def websocket_disconnect(self, message):
        # 客户端向服务端断开连接时，自动触发
        print("连接断开！！")
        self.group_name = self.scope['url_route']['kwargs']['group']

        async_to_sync(self.channel_layer.group_discard)(
            self.group_name,
            self.channel_name
        )
        raise StopConsumer()

    # 自定义的处理房间组内的数据
    def send_to_chrome(self, event):
        try:
            data = event.get('data')
            # 接收房间组广播数据，将数据发送给websocket
            self.send(json.dumps(data, ensure_ascii=False))
        except Exception as e:
            pass
